package com.servertrack

import com.commonProject.common.intefaces.ITimes
import com.commonProject.common.classes.TimesDTO;
import com.commonProject.common.exception.ValidateException
import org.springframework.context.MessageSource


class TimesService implements ITimes{
	static transactional = true
	MessageSource messageSource
	
	List<TimesDTO> getlist(Long times_id){		
			
		List<TimesDTO> dtolist=new ArrayList<TimesDTO>()
		Hotel hotelTo=Hotel.get(times_id)
		TimesDTO dto=null
		
		List<Times>time=Times.findAllByHotel(hotelTo)		  
			time.each{
				dto=new TimesDTO()
				dto.title=it.title
				dto.id=("Times_"+it.id)
				dtolist<<dto
		}
		
		return dtolist
	}
	
	TimesDTO getelement(Long times_id){
		def el=Times.get(times_id)
		
		TimesDTO dto=new TimesDTO()		
		dto.id=el.id;
		dto.title=el.title
		dto.price=el.price
		dto.dateCreated=el.dateCreated
		
		return dto
	}
	
	TimesDTO deleteElement(Long times_id){		
		def el=Times.get(times_id)
		el.delete()		
	}
	
	public void addElement(Long times_id,String times_title,Integer times_price)  throws ValidateException {
		def hotel=Hotel.get(times_id)
		println("Add Times SERVER")
		
		if (hotel) {
			Times newTimes=new Times()
			newTimes.title=times_title
			newTimes.price=times_price
			newTimes.dateCreated=new Date()			
			newTimes.hotel=hotel
			
			if (!newTimes.save()){			
				def err = newTimes.errors.allErrors.collect{[
					errorMessage:messageSource.getMessage(it, null)			
				]}
				throw new ValidateException(err)				
			}		
		}
	}
	
	public void editElement(Long times_id,String times_title,Integer times_price,String times_dateCreated) throws  ValidateException{
		def time=Times.get(times_id)
		println("Edit Times SERVER")
		time.title=times_title;
		time.price=times_price;
		if (times_dateCreated){
			time.dateCreated = new Date(times_dateCreated)
		}else{
			time.dateCreated = null
		}		
		if (!time.save()){			
				def err = time.errors.allErrors.collect{[
					errorMessage:messageSource.getMessage(it, null)			
				]}
				throw new ValidateException(err)				
			}
	}
}
